/**
 * The contents of this file are subject to the license and copyright detailed in the LICENSE and NOTICE files at the root of the source tree and available online at
 * http://www.askosi.org/license.html
 */package be.destin.skos.core;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;

import org.apache.log4j.Logger;

import be.destin.util.RunCommand;
import be.destin.util.Util;

public class TextTable implements Closeable {

	/** log4j category */
	private static Logger log = Logger.getLogger(TextTable.class);
	
	final static char BYTE_ORDER_MARK = '\uFEFF';

	String textFileName = "";
	// String tableName;
	// TODO: InputStreamReader namesFile = null;
	FileReader namesFile = null;
	BufferedReader namesBuffer;
	String[] headers;
	int lineNumber = 0;

	private String cleanField (String field) {
		String result = field;
		if (result.length()>=2 && result.charAt(0)=='"' && result.charAt(result.length()-1)=='"')
			result = result.substring(1, result.length()-1);
		result = Util.replaceAllNoRegExp(result,"\"\"", "\"");
		return result.trim();
	}

	TextTable (ConceptScheme aScheme, String rootFileName, String tableName) {
		try {
			textFileName = rootFileName+"-"+tableName+".txt";
			namesFile = new FileReader(textFileName)/*TODO: InputStreamReader(new FileInputStream(textFileName), "UTF8")*/;
			if (namesFile != null) {
				namesBuffer = new BufferedReader(namesFile);
				String header = namesBuffer.readLine();
				if (header == null) {
					log.debug("Headers line missing in "+textFileName);
				} else {
					if ((header.length() >= 1) && (header.charAt(0) == BYTE_ORDER_MARK))
						header = header.substring(1); // Remove Unicode BOM (Byte Order Marker)
					lineNumber++;
					headers = header.split("\t");
					for (int i=0; i < headers.length; i++) {
						headers[i] = cleanField(headers[i]);
					}
					log.debug(rootFileName+"-"+tableName+".txt, headers="+header+" ("+headers.length+")");
				}
			}
		} catch(IOException e) {
			String message = "File "+rootFileName+"-"+tableName+".txt is not found.";
			log.info(message);
//			aScheme.getErrors().add(message);
		}
	}

	void missingField (ConceptScheme aScheme, String field) {
		String message = aScheme.getAbout()
		+ ": \""+field+"\" field is not in the tab-delimited file "
		+ textFileName +", line no."+lineNumber;
		log.error(message);
		aScheme.getErrors().add(message);
	}

	HashMap<String,String> readRow() {
		if (namesFile == null) return null;
		HashMap<String,String> rs = null;
		try {
			String line = namesBuffer.readLine();
			lineNumber++;
			while (line!=null) {
				String[] fields = line.split("\t");
				if (fields.length > 0) {
					rs = new HashMap<String,String>();
					for (int i=0; i < fields.length; i++) {
						if (i >= headers.length) break;
						if (headers[i].length()>0) {
							rs.put(headers[i],cleanField(fields[i]));
						}
					}
					break;
				}
				line = namesBuffer.readLine();
				lineNumber++;
			}
		} catch(IOException e) {
		}
		return rs;
	}
	
	public void close() {
		RunCommand.closeAble(namesFile, "reading text table "+textFileName);
	}
}
